<template>
	<view>
		<!-- <swiper style="height: 300rpx;" autoplay circular>
			<swiper-item>
				<view style="width: 100%;height: 300rpx;background-color: red;">1</view>
			</swiper-item>
			<swiper-item>
				<view style="width: 100%;height: 300rpx;background-color: blue;">2</view>
			</swiper-item>
		</swiper> -->

		<view class="timer-bg">
			<view class="timer-display">用时：{{ formatTime(elapsedTime) }}</view>
			<!-- 重新开始按钮（进行中显示） -->
			<button v-if="hasStarted && !gameCompleted" class="restart-btn" @click="restartGame">
				重新开始
			</button>
		</view>


		<view v-if="!gameCompleted" class="bubbles-container">
			<view v-for="(bubble, index) in bubbles" :key="index"
				:class="['bubble', bubble.status, { selected: selectedIndex === index }]"
				:style="{ backgroundColor: bubble.color }" @click="handleBubbleClick(index)">
				<view class="character">{{ bubble.character }}</view>
				<view class="pinyin" v-if="bubble.type === 'pinyin'">{{ bubble.pinyin }}</view>
			</view>
		</view>

		<view v-if="gameCompleted" class="completion-message">
			<template v-if="isNewRecord">
				<view class="cup-bg">
					<image class="cup-image" src="/static/cup.png"></image>
				</view>

				<view>
					<view class="cup-bg">
						<image class="fireworks" src="/static/fireworks.png"></image>
						<view class="completion-text">新纪录</view>
						<image class="fireworks" src="/static/fireworks.png"></image>
					</view>
					<view class="record">🌟创造了新的最快记录!🌟</view>
				</view>
			</template>

			<template v-else>
				<view class="cup-bg">
					<image class="cup-image" src="/static/cup-normal.png"></image>
				</view>
				<view class="completion-text">恭喜你挑战成功!</view>
			</template>

			<!-- 再玩一次按钮（完成后显示） -->
			<button class="play-again-btn" @click="restartGame">
				继续挑战
			</button>
		</view>

		<view class="tip">
			<view>💡 玩法提示 💡</view>
			<view>✓ 汉：点击汉字泡泡选择生字</view>
			<view>✓ 拼：再点击对应的拼音泡泡</view>
			<view>✓ 正确配对后泡泡会消失，配对完所有生字即可过关！</view>
			<view>✓ 点击任意开始计时，挑战最快完成时间记录！！！</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted
	} from 'vue'
	import {
		onLoad,
		onUnload,
		onShareAppMessage
	} from '@dcloudio/uni-app'
	import {
		firstClass,
		secondClass,
		thirdClass,
		fourthClass,
		fifthClass
	} from './baby.js'
	// 用户信息
	const userInfo = ref()
	// 获取当前最快记录
	const record = ref()
	// 是否新纪录
	const isNewRecord = ref(true)
	// 小学语文二年级生字和拼音数据
	const classKey = ref() //默认null
	const classBoard = ref({})
	const wordData = ref([]) //默认为空
	// 泡泡颜色数组
	const bubbleColors = [
		'#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4',
		'#FECA57', '#FF9FF3', '#54A0FF', '#5F27CD',
		'#00D2D3', '#FF9F43', '#10AC84', '#EE5A24'
	]
	// 泡泡数组 - 存储所有泡泡的状态和数据
	const bubbles = ref([])
	// 当前选中的泡泡索引 - 用于记录第一次点击的泡泡
	const selectedIndex = ref(null)
	// 完成状态 - 标记是否全部匹配完成
	const gameCompleted = ref(false)

	// 计时相关变量
	const gameStartTime = ref(null) // 开始时间
	const elapsedTime = ref(0) // 已用时间（秒）
	const timerInterval = ref(null) // 计时器间隔
	const hasStarted = ref(false) // 是否已经开始（第一次点击）

	// 初始化
	const initGame = () => {
		wordData.value = getRandomElements()
		// 重置状态
		gameCompleted.value = false
		elapsedTime.value = 0
		hasStarted.value = false

		// 创建配对数据（每个字出现两次：一次显示字，一次显示拼音）
		const pairedData = []

		wordData.value.forEach((word, index) => {
			// 生字泡泡
			pairedData.push({
				...word,
				type: 'character', // 泡泡类型：显示生字
				color: bubbleColors[index % bubbleColors.length], // 分配颜色
				status: 'active', // 泡泡状态：活跃
				pairIndex: index * 2 + 1 // 配对索引
			})

			// 拼音泡泡
			pairedData.push({
				character: '', // 生字为空
				pinyin: word.pinyin, // 显示拼音
				type: 'pinyin', // 泡泡类型：显示拼音
				color: bubbleColors[index % bubbleColors.length], // 分配相同颜色
				status: 'active', // 泡泡状态：活跃
				pairIndex: index * 2 // 配对索引
			})
		})

		// 随机打乱顺序
		bubbles.value = pairedData.sort(() => Math.random() - 0.5)
	}

	// 重新开始
	const restartGame = () => {
		// 停止当前计时器
		stopTimer()
		// 重新初始化
		initGame()
	}

	// 开始计时器
	const startTimer = () => {
		gameStartTime.value = Date.now()
		hasStarted.value = true

		// 清除之前的计时器（如果有）
		if (timerInterval.value) {
			clearInterval(timerInterval.value)
		}

		// 每秒更新一次用时
		timerInterval.value = setInterval(() => {
			elapsedTime.value = Math.floor((Date.now() - gameStartTime.value) / 1000)
		}, 1000)
	}

	// 停止计时器
	const stopTimer = () => {
		if (timerInterval.value) {
			clearInterval(timerInterval.value)
			timerInterval.value = null
		}
	}

	// 格式化时间显示（将秒转换为分:秒格式）
	const formatTime = (seconds) => {
		const minutes = Math.floor(seconds / 60)
		const remainingSeconds = seconds % 60
		return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
	}

	// 处理泡泡点击事件
	const handleBubbleClick = (index) => {
		const bubble = bubbles.value[index]

		// 如果泡泡已经匹配或者是非活跃状态，则不处理
		if (bubble.status !== 'active') return

		// 如果是第一次点击，开始计时
		if (!hasStarted.value) {
			startTimer()
		}

		if (selectedIndex.value === null) {
			// 第一次点击 - 记录选中的泡泡
			selectedIndex.value = index
		} else {
			// 第二次点击 - 检查是否匹配
			const firstBubble = bubbles.value[selectedIndex.value]
			const secondBubble = bubble

			// 检查是否匹配（生字和拼音对应）
			const isMatch =
				(firstBubble.type === 'character' && secondBubble.type === 'pinyin' &&
					wordData.value.find(w => w.character === firstBubble.character)?.pinyin === secondBubble.pinyin) ||
				(firstBubble.type === 'pinyin' && secondBubble.type === 'character' &&
					wordData.value.find(w => w.pinyin === firstBubble.pinyin)?.character === secondBubble.character)

			if (isMatch) {
				// 匹配成功，消除泡泡
				bubbles.value[selectedIndex.value].status = 'matched'
				bubbles.value[index].status = 'matched'

				// 检查是否完成
				checkGameCompletion()
			} else {
				// 不匹配，重置选择
				setTimeout(() => {
					selectedIndex.value = null
				}, 500)
			}

			selectedIndex.value = null
		}
	}

	// 检查是否全部完成
	const checkGameCompletion = () => {
		const allMatched = bubbles.value.every(bubble => bubble.status === 'matched')
		if (allMatched) {
			gameCompleted.value = true
			stopTimer() // 完成，停止计时

			if (!record.value || elapsedTime.value < record.value) {
				isNewRecord.value = true

				try {
					uni.setStorageSync("leaderboard", {
						...classBoard.value,
						[classKey.value]: elapsedTime.value
					});
					record.value = elapsedTime.value
				} catch (e) {
					console.log(e)
				}

				if (userInfo.value) {
					uniCloud.callFunction({
						name: "update-leaderboard",
						data: {
							userId: userInfo.value.userId,
							subjectName: classKey.value,
							value: elapsedTime.value
						}
					}).then(({
						result: e
					}) => {
						console.log('cf', e)
					}).catch((e) => {
						console.log(e)
					})
				}
			} else {
				isNewRecord.value = false
			}
		}
	}

	onLoad((option) => {
		classKey.value = option.key
		// console.log('option',option)
		try {
			const value = uni.getStorageSync("leaderboard");
			if (value) {
				classBoard.value = value
				if (value[option.key]) {
					record.value = value[option.key]
				}

			}
		} catch (e) {
			console.log(e)
		}

		try {
			const value = uni.getStorageSync(`userInfo`);
			if (value) {
				userInfo.value = value
			}
		} catch (e) {
			console.log(e)
		}

		initGame()
	})
	// 组件卸载时清理计时器
	onUnload(() => {
		stopTimer()
	})
	
	onShareAppMessage((res)=>{
		if (res.from === 'button') { // 来自页面内分享按钮
			console.log(res.target)
		}
		return {
			title: '挑战新纪录！等你来闯关',
			path: '/pages/baby/chinese/baby1/index?key=chineseFirst'
		}
	})
	
	// 随机取数据
	function getRandomElements() {
		let arr = []
		switch (classKey.value) {
			case "chineseFirst":
				arr = firstClass
				break;
			case "chineseSecond":
				arr = secondClass
				break;
			case "chineseThird":
				arr = thirdClass
				break;
			case "chineseFourth":
				arr = fourthClass
				break;
			default:
				arr = fifthClass
				break;
		}
		// 复制原数组以避免修改原始数据
		const copy = [...arr];
		const result = [];
		const count = Math.min(getApp().globalData.babyCount, copy.length); // 取数组长度和12中的较小值

		for (let i = 0; i < count; i++) {
			// 生成随机索引
			const randomIndex = Math.floor(Math.random() * copy.length);
			// 从复制的数组中取出该元素并添加到结果数组
			result.push(copy.splice(randomIndex, 1)[0]);
		}

		return result;
	}
</script>

<style>
	@import "index.css"
</style>